import 'package:flutter/material.dart';
import 'package:flutter_1/utils/db/DatabaseHelper.dart';
import 'package:flutter_1/utils/db/InsertUser.dart';
import 'package:flutter_1/utils/language/message.dart';
import 'package:flutter_1/utils/style.dart';
import 'package:get/get.dart';

/// 创建用户
class UserCreatePage extends StatefulWidget {
  const UserCreatePage({super.key});

  @override
  State<UserCreatePage> createState() => _UserCreatePageState();
}

class _UserCreatePageState extends State<UserCreatePage> {
  final _formKey = GlobalKey<FormState>();
  // 用户名
  final _userNameController = TextEditingController();
  // 密码
  final _psdController = TextEditingController();
  // 姓名
  final _nameController = TextEditingController();

  // 联系电话
  final _contactPhoneController = TextEditingController();
  // 邮箱
  final _emailController = TextEditingController();

  String? _selectedCustomerCode;
  final List<String> _customerCodes = [Strem.trader, Strem.client];

  @override
  void initState() {
    super.initState();
  }

  /// 插入数据
  insertData() async {
    // ignore: unrelated_type_equality_checks
    if (_customerCodes == Strem.trader) {
      // 贸易商插入数据

      var result = await DatabaseHelper.query('Merchant_table',
          where: 'merchant_name = ?', whereArgs: [_userNameController.text]);
      if (result.isEmpty) {
        // 插入数据
        await DatabaseHelper.insert("Merchant_table", {
          "merchant_name": _userNameController.text,
          "phone": _contactPhoneController.text,
          "password": _psdController.text
        });
      } else {
        // 数据已存在
        debugPrint('ID already exists');
      }
    } else {
      // 用户插入数据
      try {
        await Insertuser.insert(
            _userNameController.text,
            _nameController.text,
            _psdController.text,
            _contactPhoneController.text,
            _emailController.text);
      } catch (e) {
        debugPrint("Error: $e");
        // 可以展示给用户相关的提示
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Strem.createAUser,
            style: Style.c_white_size18_bold, textAlign: TextAlign.left),
        backgroundColor: Style.c_8cd5ff, // 设置AppBar背景色
        automaticallyImplyLeading: false, // 确保不显示返回按钮
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(Strem.role, style: const TextStyle(fontSize: 16)),
                  const SizedBox(height: 5),
                  _buildCustomDropdown(),
                ],
              ),
              const SizedBox(height: 16),
              _buildTextField(Strem.username, controller: _userNameController),
              _buildTextField(
                Strem.psd,
                controller: _psdController,
              ),
              _buildTextField(Strem.name, controller: _nameController),
              _buildTextField(Strem.contactNumber,
                  controller: _contactPhoneController, isNumber: true),
              _buildTextField(Strem.email, controller: _emailController),
              const SizedBox(height: 20),
              GestureDetector(
                onTap: () {
                  if (_formKey.currentState!.validate()) {
                    // 客户代码
                    if (_selectedCustomerCode == null ||
                        _selectedCustomerCode == "") {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.customerCode}${Strem.unempty}',
                      );
                      return;
                    }
                    // 用户名
                    if (_userNameController.text == "") {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.productName}${Strem.unempty}',
                      );
                      return;
                    }
                    // 联系电话
                    if (_contactPhoneController.text.length != 11) {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.contactNumber}${Strem.enterError}',
                      );
                      return;
                    }
                    // 联系电话
                    if (!_emailController.text.contains("@")) {
                      Get.snackbar(
                        Strem.error,
                        '${Strem.email}${Strem.enterError}',
                      );
                      return;
                    }
                    insertData();
                    // 提示用户订单提交成功
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text(Strem.createSuccessful)),
                    );
                    Get.back();
                  }
                },
                child: Container(
                  margin: const EdgeInsets.only(bottom: 20),
                  width: MediaQuery.of(context).size.width - 32,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Style.c_8cd5ff,
                      borderRadius: BorderRadius.circular(5)),
                  child: Text(
                    Strem.createAUser,
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Get.back();
                },
                child: Container(
                  margin: const EdgeInsets.only(bottom: 20),
                  width: MediaQuery.of(context).size.width - 32,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Style.c_back38,
                      borderRadius: BorderRadius.circular(5)),
                  child: Text(
                    Strem.cancel,
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 自定义下拉菜单
  Widget _buildCustomDropdown() {
    return GestureDetector(
      onTap: () {
        showMenu<String>(
          context: context,
          position: RelativeRect.fromLTRB(
            16, // 距离左边的距离
            150, // 距离顶部的距离（根据需要调整）
            MediaQuery.of(context).size.width - 16, // 距离右边的距离
            MediaQuery.of(context).size.height - 100, // 距离底部的距离
          ),
          items: _customerCodes.map((code) {
            return PopupMenuItem<String>(
              value: code,
              child: Text(code),
            );
          }).toList(),
          elevation: 8.0,
        ).then((value) {
          if (value != null) {
            setState(() {
              _selectedCustomerCode = value;
            });
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(_selectedCustomerCode ?? Strem.selectCode),
            const Icon(Icons.arrow_drop_down),
          ],
        ),
      ),
    );
  }

  // 统一样式的文本输入框组件
  Widget _buildTextField(String label,
      {required TextEditingController controller, bool isNumber = false}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(fontSize: 16)),
        const SizedBox(height: 5),
        TextFormField(
          controller: controller,
          keyboardType: isNumber ? TextInputType.number : TextInputType.text,
          decoration: InputDecoration(
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
              borderSide: const BorderSide(color: Colors.grey), // 设置边框颜色
            ),
          ),
          validator: (value) =>
              value!.isEmpty ? '$label${Strem.unempty}' : null,
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  @override
  void dispose() {
    _userNameController.dispose();
    _psdController.dispose();
    _nameController.dispose();
    _contactPhoneController.dispose();
    super.dispose();
  }
}
